<template>
    <div class="container">
        <div class="userinfo" @click="login">
            <img :src="userInfo.avatarUrl" alt="">
            <p>{{userInfo.nickName}}</p>
        </div>
        <YearProgress></YearProgress>
        <button @click='scanBook' class="btn">添加图书</button>
    </div>
</template>

<script>
  import YearProgress from '@/components/yearProgress'
  import { post, showSuccess } from '../../util'
  import qcloud from 'wafer2-client-sdk'
  import config from '../../config'
export default {
    components: {
      YearProgress
    },
    data () {
      return {
        userInfo: {
          avatarUrl: '/static/images/unlogin.png',
          nickName: '点击登陆'
        }
      }
    },
    methods: {
      async addBook (isbn) {
        console.log(isbn)
        const res = await post('/weapp/hello', {
          isbn,
          openid: this.userInfo.openId
        })
        if (res.code === 0 && res.data.title) {
          showSuccess('添加成功', `${res.data.title}添加成功`)
        }
      },
      scanBook () {
        wx.scanCode({
          success: (res) => {
            this.addBook(res.result)
          },
          fail: err => {
            console.log(err)
          }
        })
      },
      login (e) {
        let user = wx.getStorageSync('userInfo')
        if (!user) {
          qcloud.setLoginUrl(config.loginUrl)
          qcloud.login({
            success: (userInfo) => {
              qcloud.request({
                url: config.userUrl,
                login: true,
                success: userRes => {
                  showSuccess('登陆成功')
                  console.log(userRes)
                  wx.setStorageSync('userInfo', userRes.data.data)
                  this.userInfo = userRes.data.data
                }
              })
            },
            fail: function (err) {
              console.log('登录失败', err)
            }
          })
        }
      }
    },
    onShow () {
      let userInfo = wx.getStorageSync('userInfo')
      if (userInfo) {
        this.userInfo = userInfo
      }
    }
}
</script>

<style lang='scss'>
.container{
    padding: 0 30rpx;
    box-sizing: border-box;
    .userinfo{
        margin-top:100rpx;
        text-align: center;
        img{
            width: 150rpx;
            height: 150rpx;
            margin: 20rpx;
            border-radius: 50%
        }
    }
    .btn{
      margin-top: 20rpx;
    }
}
</style>
